package cn.crex1.springboot.securitydemo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthencationSuccessHandler authencationSuccessHandler;

    @Autowired
    private AuthencationFailHandler authencationFailHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login.html").permitAll()
//                .antMatchers("/hello").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login.html").loginProcessingUrl("/sys/login")
                .successHandler(authencationSuccessHandler)
                .failureHandler(authencationFailHandler)
                .and()
                .logout().logoutUrl("/sys/logout").logoutSuccessUrl("/login.html")
                .and().rememberMe().rememberMeCookieName("jizhuwo").userDetailsService(userDetailsService).and().sessionManagement().invalidSessionUrl("/login.html").and()
                .csrf().disable();
    }

    @Override
    public void init(WebSecurity web) throws Exception {
        web.debug(true);
        super.init(web);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
